﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Odyssey.Linq;
using SunTzu.Web;
using System.IO;
using Rea.Web.Models;
using SunTzu.Core.Data;
using Odyssey.Web.Models;

namespace Odyssey.Web.Controllers
{
    public class ProjectController : FrontBaseController
    {
        public ActionResult Detail(int id)
        {
            form_project entity = db.form_projects.FirstOrDefault(c => c.Id == id);
            ViewData.Model = entity ?? new form_project();
            BindMasterViewData(3);
            return View();
        }

        [Login]
        public ActionResult New(int? id)
        {
            if (id.HasValue)
            {
                ViewData.Model = db.form_projects.FirstOrDefault(c => c.Id == id.GetValueOrDefault() && c.AccountId == LoginHelper.CurrentUserId);
            }
            else
            {
                ViewData.Model = new form_project();
            }
            return View();
        }

        public ActionResult MyProjects()
        {
            ViewData.Model = db.form_projects.Where(c => c.AccountId == LoginHelper.CurrentUserId).OrderByDescending(c => c.CreateDate).ToList();
            return View();
        }

        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateProject(int? id)
        {
            form_project project;
            if (id.GetValueOrDefault() > 0)
            {
                project = db.form_projects.FirstOrDefault(c => c.Id == id.GetValueOrDefault() && c.AccountId == LoginHelper.CurrentUserId);
            }
            else
            {
                project = new form_project();
            }

            HTMLHelper.BindModel(project);
            project.AccountId = LoginHelper.CurrentUserId;
            if (project.SaveOrUpdate())
            {
                SetMessage("保存成功！");
            }

            return RedirectToAction("MyProjects");
        }

        public ActionResult List(int? subcategory, int? page)
        {
            PagedList<form_project> projectList = null;
            if (subcategory.HasValue)
            {
                var sub = subcategory.ToString();
                projectList = db.form_projects
                    .Where(c => c.State == 1 && c.ProjectType0.Contains(sub))
                    .ToPagedList(page.GetValueOrDefault());

                ViewBag.SubClassName = ViewHelper.GetProjectTypeName(sub);
            }
            ViewBag.Projects = projectList ?? new List<form_project>().ToPagedList(page.GetValueOrDefault());
            BindMasterViewData(3);
            return View();
        }
    }
}
